package echat.future.cn.echat.my.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallAdapter;
import com.fm.openinstall.listener.AppWakeUpAdapter;
import com.fm.openinstall.model.AppData;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Observer;

import echat.future.cn.echat.AppApplication;
import echat.future.cn.echat.MainActivity;
import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.ActivityLoginBinding;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.api.WxApi;
import echat.future.cn.echat.my.bean.Token;
import echat.future.cn.echat.my.bean.UserBean;
import echat.future.cn.echat.my.bean.WxInfoBean;
import echat.future.cn.echat.my.http.RetrofitClient;
import echat.future.cn.echat.my.utils.Contancts;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.PhoneUtils;
import echat.future.cn.echat.my.utils.RxUtils;
import echat.future.cn.echat.my.utils.ToastUtils;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.weight.Navagation.AdapterNavagation;
import echat.future.cn.echat.my.weight.Navagation.IBaseNavagation;
import echat.future.cn.echat.netease.CheckSumBuilder;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> implements
        View.OnClickListener{

    @Override
    public int layoutId() {
        return R.layout.activity_login;
    }

    @Override
    public IBaseNavagation navagation() {
        return new AdapterNavagation(this).setTitle(this.getResources().getString(R.string.login_title),16,R.color.color_333333).setBack();
    }

    @SuppressLint("CheckResult")
    @Override
    public void initView() {
        if(UserHelper.getUser() !=null){
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }
        RxUtils.clickView(bind.login).subscribe(view -> {
            onClick(view);
        });
        bind.tvRegister.setOnClickListener(this);
        bind.tvForget.setOnClickListener(this);
        bind.agreement.setOnClickListener(this);
        RxUtils.clickView(bind.qq).subscribe(view -> qqLogin());
        RxUtils.clickView(bind.weixin).subscribe(view -> wxLogin());
        setAgreement();

        OpenInstall.getInstall(new AppInstallAdapter() {
            @Override
            public void onInstall(AppData appData) {
                //获取渠道数据
                getPid(appData.getData());
            }
        });

        OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);

//        startActivity(new Intent(this,MainActivity.class));
//        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, wakeUpAdapter);
    }
    AppWakeUpAdapter wakeUpAdapter = new AppWakeUpAdapter() {
        @Override
        public void onWakeUp(AppData appData) {
            //获取渠道数据
            //获取绑定数据  {"id":"10"}
            getPid(appData.getData());
        }
    };

    private void getPid(String json){
        try {
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(json);
            if (jsonElement.isJsonObject()){
                if(jsonElement.getAsJsonObject().has("id")){
                    MyApplication.getInstance().pid = jsonElement.getAsJsonObject().get("id").getAsString();
                    System.out.println("MyApplication.getInstance().pid="+MyApplication.getInstance().pid);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    public void setAgreement(){
        SpannableString spanString = new SpannableString(this.getResources().getString(R.string.agreement));
        ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
        spanString.setSpan(span, spanString.length()-6, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        bind.agreement.append(spanString);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_register:
                RegisterActivity.openActivity(this,RegisterActivity.class);
                break;
            case R.id.login:
                login();
                break;
            case R.id.tv_forget:
                ForgetActivity.openActivity(this,ForgetActivity.class);
                break;
            case R.id.agreement:
                UserProtocolActivity.openActivity(this,UserProtocolActivity.class);
                break;
        }
    }


    /**
     * 普通登陆
     */
    private void login(){
        if(!PhoneUtils.isMobile0(bind.phone.getText().toString())){
            ToastUtils.toastMsg(LoginActivity.this,"请输入正确的手机号码");
            return;
        }
        if(!PhoneUtils.isPass(bind.pass.getText().toString())){
            ToastUtils.toastMsg(LoginActivity.this,"请输入正确的密码");
            return;
        }
        String md5Pass = MD5.Md5(bind.pass.getText().toString()).toUpperCase();
       Observable observable =  HttpUtilsRequst.retrofitClient.create(UserApi.class).login(bind.phone.getText().toString(),md5Pass)
               .flatMap(tokenBaseVo -> {
                   //保存token令牌，开始获取用户信息
                   if(tokenBaseVo.getCode() == 1){
                       UserHelper.saveToken(tokenBaseVo.getData());
                       String key = "9b4aaf?&&##664bdef@c3fc3efa9";
                       return HttpUtilsRequst.retrofitClient.create(UserApi.class).getUserInfo(tokenBaseVo.getData().getToken(),MD5.Md5(System.currentTimeMillis()/1000+key).toLowerCase());
                   }else{
                       throw new Exception(tokenBaseVo.getMsg());
                   }
               });

        new HttpUtilsRequst<Token>(this,observable)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<UserBean>) userInfo -> {
                    UserHelper.save(userInfo);
                    SharedPreference.saveToSP(LoginActivity.this,"phone",bind.phone.getText().toString());
                    MyApplication.getInstance().setPhone(bind.phone.getText().toString());
                    ToastUtils.toastMsg(LoginActivity.this,"登陆成功");
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }).start();
    }


    /**
     * 第三方登陆
     * @param authType 1 微信 2 QQ
     * @param openId
     */
    private void secondLogin(int authType,String openId){
        Observable observable =  HttpUtilsRequst.retrofitClient.create(UserApi.class).sencodeLogin(openId,authType)
                .flatMap(tokenBaseVo -> {
                    //保存token令牌，开始获取用户信息
                    if(tokenBaseVo.getCode() == 1){
                        UserHelper.saveToken(tokenBaseVo.getData());
                        if(tokenBaseVo.getData().getMobile() == null || tokenBaseVo.getData().getMobile().equals("")){
                            //当前登陆没有绑定账户
                            startActivity(new Intent(LoginActivity.this,BindPhoneActivity.class).
                                    putExtra("openId",openId)
                            .putExtra("authType",authType));
                            finish();
                            throw new Exception("请前往绑定手机号码");
                        }
                        String key = "9b4aaf?&&##664bdef@c3fc3efa9";
                        return HttpUtilsRequst.retrofitClient.create(UserApi.class).getUserInfo(tokenBaseVo.getData().getToken(),MD5.Md5(System.currentTimeMillis()/1000+key).toLowerCase());
                    }else{
                        throw new Exception("登陆失败");
                    }
                });

        new HttpUtilsRequst<Token>(this,observable)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<UserBean>) userInfo -> {
                    UserHelper.save(userInfo);
                    ToastUtils.toastMsg(LoginActivity.this,"登陆成功");
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode,resultCode,data,loginListener);
        super.onActivityResult(requestCode, resultCode, data);
    }




    IUiListener loginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            JSONObject jsonObject = (JSONObject) o;
            try {
                //唯一Id
                String openId = jsonObject.getString("openid");
                secondLogin(2,openId);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            toast(uiError.errorMessage);
        }

        @Override
        public void onCancel() {
            toast("取消QQ登陆");
        }
    };
    private void qqLogin(){
        if (!AppApplication.tencent.isSessionValid())
        {
            AppApplication.tencent.login(this, "all", loginListener);
        }
    }

    /**
     * 微信登陆
     */
    private void wxLogin(){
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "none";
        ((AppApplication)getApplication()).getIwxapi().sendReq(req);
    }

    Observer observer = new Observer() {
        @Override
        public void update(java.util.Observable o, Object arg) {
            new RetrofitClient(LoginActivity.this,"https://api.weixin.qq.com/").getRetrofit()
            .create(WxApi.class).getWxInfo(Contancts.WECHAT_APPID,Contancts.WECHAT_APPSEREA,AppApplication.wxLoginBean.getCode(),"authorization_code")
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new io.reactivex.Observer<WxInfoBean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(WxInfoBean wxInfoBean) {
                    //用户使用微信登陆
                    secondLogin(1,wxInfoBean.getOpenid());
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            })
            ;

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppApplication.wxLoginBean.addObserver(observer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppApplication.wxLoginBean.deleteObserver(observer);
        wakeUpAdapter = null;
    }


}
